<?php
namespace Home\Controller;

use Utuo\ForegroundController;

class ActivityScratchController extends ForegroundController {
	
	public function _init() {
		$this->checkLogin();
	}
	
    public function indexAction() {
    	$this->display();
    }
    
    /**
     * 刮刮卡
     */
    public function showAction() {
    	$activityId = I("id", 0, "intval"); // 活动id
    	$activityScratch = $this->getScratch($activityId);
    	if(!$activityScratch) { $this->error("活动未找到或已过期", url("Home","Site","index", "sid={$this->sid}"));  exit;}
    	$this->assign("activityScratch", $activityScratch);
    	$this->display();
    }
    
    /**
     * 刮刮卡抽奖
     */
    public function savePostAction() {
    	$activityId = I("id", 0, "intval"); // 活动id
    	$activityScratch = $this->getScratch($activityId);
    	$activityScratch and $this->ajaxError("活动未找到或已过期");
    	/*检查之前的抽奖记录*/
    	$m = M("activityRecord");
    	$scratchRecord = $m->where(array(
				    			'uid' => $this->uid,
				    			'cid' => $this->cid,
				    			'ac_id' => $activityScratch['id'],
				    	))->find();
    	if($scratchRecord) {
    		date("Ymd") == $scratchRecord['date'] and $scratchRecord['times'] > $activityScratch['day_times'] and $this->ajaxError("今日最多刮".$activityScratch['day_times']."次");
    		date("Ymd") == $scratchRecord['date'] and $scratchRecord['prize'] > 0 and $this->ajaxError("今日已中奖，不能在刮了!");
    		$scratchRecord['date'] = date("Ymd");
    		$scratchRecord['times'] = 0;
    		$scratchRecord['prize'] = 0;
    		$m->save($scratchRecord);
    	}else{
    		$id = $m->add(array(
    				'cid' => $this->cid,
    				'uid' => $this->uid,
    				'ac_id' => $activityScratch['id'],
    				'date' => date("Ymd"),
    		)) and false !== $id or $this->ajaxError("刮奖信息保存失败，请重试");
    		$scratchRecord = $m->find($id);
    	}
    	/*抽奖过程*/
    	$prizeConfig = $activityScratch['prize_config']; // 活动奖项配置
    	$prize = $this->getRand($prizeConfig);
    	/*计算奖项*/
    	if($prize[0]) {
    		$index = $prize[1];
    		do{
    			$currentPrize = $prizeConfig[$index];
    			$prize[0] = $currentPrize['level'];
    			$prize[1] = $index;
    			$index++;
    		}while($index < count($prizeConfig) && $currentPrize['count'] == $currentPrize['total']); // 名额已满时继续
    		// 奖项已抽完
    		if($index == count($prizeConfig)) {
    			$prize = array(0, -1);
    		}
    	}
    	/*保存抽奖记录*/
    	$data = array("times" => $scratchRecord['times']+1, "date"=>date("Ymd")) and $prize[0] and $data['prize'] = $prize[0];
    	$m->where("id=%d", $scratchRecord["id"])->save($data);
    	/*更新显示抽奖活动信息*/
    	if($prize[0]){
    		$prizeConfig['count'] = $prizeConfig['count'] + 1;
    		M("Activity")->where("id=%d", $activityId)->setField("prize_config", serialize($prizeConfig));
    		$this->ajaxSuccess("恭喜您中了".$currentPrize['title'].":".$currentPrize['prizeName']);
    	}
    	$this->ajaxSuccess("未中奖继续努力!");
    }
    
    /**
     * 获得中奖随机信息
     * @param unknown $prizeConfig
     * @param int type 0.按默认或已设定的总几率  1.从几率内取值
     * @param int sum 总几率 
     * @return number
     */
    private function getRand($prizeConfig, $type = 0, $sum = 100) {
    	if($type === 1) { // 限制从几率内取值
    		foreach ($prizeConfig as $key => $val) {
    			$arr[$val['id']] = $val['ratio'];
    		}
    		$sum = array_sum($arr);
    	}
    	//随机获得一个幸运数字
    	$luck_num = mt_rand( 0, $sum - 1 );
    	//初始化几率区间
    	$lucky_range = 0;
    	$index = -1;
    	foreach( $prizeConfig as $k => $v ){
    		$ratio = intval( $v['ratio'] );
    		if( $luck_num >= $lucky_range && $luck_num < $lucky_range + $ratio ){
    			$level = $v['level'];
    			$index = $k;
    			break;
    		}else{
    			$lucky_range += $ratio;
    		}
    	}
    	return array($level*1, $index);
    }
    
    /**
     * 获得刮刮卡活动
     * @param unknown $activityId
     * @return mixed
     */
    private function getScratch($activityId) {
    	$now = time();
    	$activityScratch = M('Activity')->where(array(
					    			'id' => $activityId,
					    			'cid' => $this->cid,
					    			'begin_time' => array("exp", " <=".$now." and end_time >".$now),
					    			'status' => 1
					    	))->find(); // 获得一个进行中的活动
    	$activityScratch and $activityScratch['prize_config'] = unserialize($activityScratch['prize_config']);
    	return $activityScratch;
    }
}